package com.utils.adapay.degree;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 汇付聚合支付加签验签
 * @author daigb
 * @date:  2022-07-18 13:41
 */
@Slf4j
@Component
public class SignTool {
	private String keyFilePath;
    @Value("${adapay.degree.password}")
	private String password;
	private String merchantAcct;
    @Value("${adapay.degree.alias}")
	private String alias;

	public static final String SIGNATUREPARAMS = "merchantAcctId,terminalId,version,payType,bankId,"
			+ "orderId,orderTime,orderCurrency,orderAmount,dealId,bankDealId,dealTime,"
			+ "ext1,ext2,payResult,errCode";

	public SignTool() {
	}

	public SignTool(String merchantAcct, String keyFilePath, String password,
			String alias) {
		this.merchantAcct = merchantAcct;
		this.keyFilePath = keyFilePath;
		this.password = password;
		this.alias = alias;
	}
	
	public String signMsg(String sourceMsg) {
		log.info("sourceMsg:" + sourceMsg);

		String signMsg = "";
		try {
//			keyFilePath += merchantAcct + ".pfx";
			keyFilePath += "adapay" + ".pfx";
			KeyStore ks = KeyStore.getInstance("PKCS12");
			FileInputStream ksfis = new FileInputStream(keyFilePath);
			BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
			char[] keyPwd = password.toCharArray();
			ks.load(ksbufin, password.toCharArray());
			PrivateKey priK = (PrivateKey) ks.getKey(alias, keyPwd);
			Signature signature = Signature.getInstance("SHA1withRSA");
			signature.initSign(priK);
			signature.update(sourceMsg.getBytes("UTF-8"));
			sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
			signMsg = encoder.encode(signature.sign());

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return signMsg;
	}

//	public String verfiy(HttpServletRequest request) throws IOException {
//		String message = null;
//		Map<String, Object> map = ServletUtils.getRequestParameters(request);
//		message = message + "notify info:" + map.toString();
//		System.out.println("messag===" + message);
//		String dataReceived = "";
//		List<String> keyList = new ArrayList<String>();
//		Set<String> set = map.keySet();
//		for (String key : set) {
//			if (SIGNATUREPARAMS.indexOf(key) >= 0 && map.get(key) != null
//					&& !StringUtils.isEmpty((String) map.get(key))) {
//				keyList.add(key);
//			}
//		}
//		Collections.sort(keyList);
//
//		for (String key : keyList) {
//			dataReceived = appendParam(dataReceived, key, (String) map.get(key));
//		}
//
//		String signMsg = (String) map.get("signMsg");
//		System.err.println("signMsg===" + signMsg);
//
//		boolean veryfyResult = false;
//		try {
//			//veryfyResult = XMLSecurityProcess.veryfySignature(dataReceived,signMsg);
//			veryfyResult = XMLSecurityProcess.veryfySignature(URLDecoder.decode(dataReceived), URLDecoder.decode(signMsg));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		message = message + "\r\n " + ":" + veryfyResult;
//		message += dataReceived;
//		return message;
//	}

	public String appendParam(String returns, String paramId, String paramValue) {
		if (returns != "") {
			if (paramValue != "") {

				returns += "&" + paramId + "=" + paramValue;
			}
		} else {

			if (paramValue != "") {
				returns = paramId + "=" + paramValue;
			}
		}
		return returns;
	}

}
